<script setup lang="ts">
import { request } from '@/api';
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { onMounted, ref } from 'vue';
import b64toBlob from 'b64-to-blob'
const profile = ref<ProfileInfo>({} as ProfileInfo)
// 1. 修改头像
// 1.1 控制修改头像弹层的显示/隐藏
const showAvatarSheet = ref(false)
// 1.2 打开相册/相机
const onSelectAvatar = async (item: ActionSheetAction, i: number) => {
    if (i === 0) {
        // 关闭头像选择框
        showAvatarSheet.value = false
        // 相册上传
        const data = await mk.pickerPhoto()
        await onUpdateAvatar(data)

    } else if (i === 1) {
        // 关闭头像选择框
        showAvatarSheet.value = false
        // 拍照上传
        const data = await mk.pickerCamera()
        await onUpdateAvatar(data)
    }
}
// 1.3 头像上传
/**
 * 更新用户头像的异步函数
 * @param {string} data - Base64编码的图片数据
 */
const onUpdateAvatar = async (data: string) => {
    try {
        // 显示加载中的Toast提示，禁止用户点击
        showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
        // 将Base64编码的图片数据转换为Blob对象
        const image = b64toBlob(data, 'image/jpeg')
        // 创建FormData对象用于上传文件
        const fd = new FormData()
        // 将Blob对象添加到FormData中，使用当前时间戳作为文件名
        fd.append('file', image, Date.now() + '.jpeg')
        // 发起POST请求上传头像
        const res = await request.post<MkResponse<{ avatar: string }>>('member/profile/avatar', fd)
        // 更新本地头像预览
        profile.value.avatar = URL.createObjectURL(image)
        // 获取当前用户信息
        const user = mk.queryUser()
        // 更新用户的头像URL
        user.avatar = res.data.result.avatar
        // 更新用户信息
        mk.updateUser(user)
        // 显示上传成功的Toast提示
        showToast({ message: '上传成功' })
    } catch {
        // 处理上传失败的情况
        showToast({ message: '上传失败' })
    }
}
// 2. 选择生日日期
const birthday = ref<string[]>([])
const showBirthdayPopup = ref(false)
const onChangeBirthday = (data: { selectedValues: string[] }) => {
    showBirthdayPopup.value = false
    profile.value.birthday = data.selectedValues.join('-')
}

// 3. 选择所在地
const areaColumns = ref<AreaColumns>()
const showLocationPopup = ref(false)
onMounted(async () => {
    showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true })
    const data = await mk.getAreaColumns()
    areaColumns.value = data
    const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
    closeToast()
    profile.value = res.data.result
    birthday.value = profile.value.birthday.split('-')
    console.log(profile.value);
})
const onSelectedLocation = (data: { selectedValues: string[], selectedOptions: { text: string }[] }) => {
    showLocationPopup.value = false
    console.log(data.selectedValues);
    // 后端表单需要提交省市区的code
    profile.value.provinceCode = data.selectedValues[0]
    profile.value.countyCode = data.selectedValues[1]
    profile.value.profession = data.selectedValues[2]
    // 前端表单需要显示完整的地址
    profile.value.fullLocation = data.selectedOptions.map(item => item.text).join(' ')

}

// 4. 选择职业
const columns = [
    { text: '软件工程师', value: '软件工程师' },
    { text: '医生', value: '医生' },
    { text: '教师', value: '教师' },
    { text: '律师', value: '律师' },
    { text: '会计师', value: '会计师' },
    { text: '销售经理', value: '销售经理' },
    { text: '市场营销专员', value: '市场营销专员' },
    { text: '建筑师', value: '建筑师' },
    { text: '护士', value: '护士' },
    { text: '机械工程师', value: '机械工程师' }
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {
    console.log(data.selectedValues);
    profile.value.profession = data.selectedValues[0]
    showProfessionPopup.value = false
}
// 提交表单
const loading = ref(false)
const onSubmit = async () => {
    loading.value = true
    await request.put('member/profile', profile.value)
    loading.value = false
    const user = mk.queryUser()
    user.nickname = profile.value.nickname
    mk.updateUser(user)
    showToast({ message: '保存成功' })
}
</script>

<template>
    <div class="profile-edit-page">
        <!-- 头像部分 -->
        <div class="avatar">
            <van-image round width="100" height="100" class="avatar-img" :src='profile.avatar'
                @click="showAvatarSheet = true">
            </van-image>
            <div class="avatar-btn">
                <span @click="showAvatarSheet = true">修改头像</span>
            </div>
        </div>
        <van-action-sheet v-model:show="showAvatarSheet" :actions="[{ name: '相册' }, { name: '拍照' }]"
            @select="onSelectAvatar" cancel-text="取消" :style="{ paddingBottom: '20px' }" />

        <!-- 中间表单部分 -->
        <van-cell-group>
            <van-field label="账号" readonly v-model="profile.account"></van-field>
            <van-field label="昵称" placeholder="请输入昵称" v-model="profile.nickname"></van-field>
            <van-cell title="性别" class="gender">
                <van-radio-group :icon-size="16" v-model="profile.gender">
                    <van-radio name="男">男</van-radio>
                    <van-radio name="女">女</van-radio>
                    <van-radio name="未知">未知</van-radio>
                </van-radio-group>
            </van-cell>
            <van-field label="生日" readonly placeholder="请选择日期" @click="showBirthdayPopup = true"
                v-model="profile.birthday"></van-field>
            <!-- 选择生日弹层 -->
            <van-popup v-model:show="showBirthdayPopup" round position="bottom">
                <van-date-picker v-model:model-value="birthday" title="选择日期" @cancel="showBirthdayPopup = false"
                    @confirm="onChangeBirthday" :min-date="new Date('1980-01-01')" />
            </van-popup>
            <van-field label="所在地" readonly placeholder="请选择所在地" @click="showLocationPopup = true"
                v-model="profile.fullLocation"></van-field>
            <!-- 选择所在地弹层 -->
            <van-popup v-model:show="showLocationPopup" round position="bottom">
                <van-area :area-list="areaColumns" @confirm="onSelectedLocation"
                    @cancel="showLocationPopup = false"></van-area>
            </van-popup>
            <van-field label="职业" readonly placeholder="请选择职业" @click="showProfessionPopup = true"
                v-model="profile.profession"></van-field>
            <!-- 打开选择职业弹层 -->
            <van-popup v-model:show="showProfessionPopup" round position="bottom">
                <van-picker :columns="columns" @confirm="onChangeProfession" @cancel="showProfessionPopup = false" />
            </van-popup>
        </van-cell-group>

        <div class="submit">
            <van-button round block type="primary" @click="onSubmit" :loading="loading">
                保存资料
            </van-button>
        </div>
    </div>
</template>

<style lang="css" scoped>
.avatar {
    padding: 30px;
    text-align: center;
    background-color: var(--mk-white);
}

.avatar-img {
    box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
    color: var(--mk-linear_end);
    margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
    width: 100px;
    flex: none;
}

.van-radio-group {
    display: flex;
    justify-content: space-between;
    height: 36px;
    width: 180px;
}

.submit {
    padding: 16px;
}
</style>